package com.kaidongyuan.app.kdydriverr.ui.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.zicox.cpcl.ConnectStateEnum;
import com.example.zicox.cpcl.IprinterListen;
import com.example.zicox.cpcl.zkBluetoothPrinter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.kaidongyuan.app.basemodule.interfaces.AsyncHttpCallback;
import com.kaidongyuan.app.basemodule.widget.loadingDialog.MyLoadingDialog;
import com.kaidongyuan.app.kdydriverr.R;
import com.kaidongyuan.app.kdydriverr.constants.Constants;
import com.kaidongyuan.app.kdydriverr.httpclient.OrderAsyncHttpClient;
import com.kaidongyuan.app.kdydriverr.ui.base.BaseActivity;
import com.kaidongyuan.app.kdydriverr.utils.AES256Utils;

//打印

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.view.Menu;

public class AdEscPrint extends BaseActivity implements AsyncHttpCallback{
    protected MyLoadingDialog myLoadingDialog;
    public static BluetoothAdapter myBluetoothAdapter;
    public zkBluetoothPrinter zkPrinter;
    public String SelectedBDAddress;
    public static Context mContext;
    public OrderAsyncHttpClient mClient;
    private final String Tag_Get_Locations = "Update_Print_Count";
    private final String Tag_Get_Locations1 = "Select_Order_By_Client_Order_No";

//    Bitmap bitmap ;
//    Bitmap bitmap_2 ;
    Bitmap bitmap_logo ;
    StatusBox statusBox;
    ConnectStateEnum mstate;
    /**
     * 返回上一界面按钮
     */
    View view;
    String Authorization;
    String cellphone;
    // 打印的json_array
    com.alibaba.fastjson.JSONArray json_array_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_sdt);
//        bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.recv);
//        bitmap_2 = BitmapFactory.decodeResource(this.getResources(), R.drawable.ji);
        bitmap_logo = BitmapFactory.decodeResource(this.getResources(), R.drawable.kzhlogo);
        int newlogoWidth = 250;
        int newlogoHeight =  73;
        int blogowidth = bitmap_logo.getWidth();
        int blogoheight = bitmap_logo.getHeight();
        // 计算缩放比例
        float scalelogoWidth = ((float) newlogoWidth) / blogowidth;
        float scalelogoHeight = ((float) newlogoHeight) / blogoheight;
        Matrix matrixlogo = new Matrix();
        matrixlogo.postScale(scalelogoWidth, scalelogoHeight);
//         得到新的图片
        bitmap_logo = Bitmap.createBitmap(bitmap_logo, 0, 0, blogowidth, blogoheight, matrixlogo,
                true);
        AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("请先在手机设置的蓝牙中连接打印机设备")
//                    .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        finish();
                    }
                })
                .create();

        if(!ListBluetoothDevice()){
            alertDialog2.show();
        };
//        zpBluetoothPrinter zpSDK1=new zpBluetoothPrinter(mContext);
        zkPrinter=new zkBluetoothPrinter(new IprinterListen()
        {
            @Override
            public void onReceiveData(byte[] arrayOfByte, int length) {
                // TODO Auto-generated method stub

                try {
                    if((arrayOfByte[0]==29)&&(arrayOfByte[0]==103))
                    {
                        byte status = arrayOfByte[2];
                        if ((status & 0x1) != 0)
                        {
                            Log.v("MainActivity","缺纸");
                            //  a = 1;
                        }
                        if ((status & 0x2) != 0)
                        {
                            Log.v("MainActivity","纸仓打开");
                        }
                    } else {
//                        Content0();
                        String scanRes = new String(arrayOfByte).substring(0, length);
                        Log.d("LM", "arrayOfByteres" + scanRes);
                        Log.d("LM", "贴标机扫描返回成功");
//                        Content0(scanRes);
                        getPrintData(scanRes);
//                        Print1(scanRes);
                    }

                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            @Override
            public void onBluetoothState(ConnectStateEnum state) {
                // TODO Auto-generated method stub
                mstate=state;

            }});
        mContext = this;
        mClient = new OrderAsyncHttpClient(AdEscPrint.this, this);
        Intent intent1 = getIntent();
        Authorization = intent1.getStringExtra("Authorization");
        cellphone = intent1.getStringExtra("cellphone");

        Button Button1 = (Button) findViewById(R.id.btPrintCustom);
        statusBox = new StatusBox(this,Button1);
        Button1.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View arg0) {
                zkPrinter.connect(SelectedBDAddress);
            }
        });
        Button Button2 = (Button) findViewById(R.id.returnjsbtn);

        statusBox = new StatusBox(this,Button2);
        Button2.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View arg0) {
                finish();
            }
        });
    }
    public JSONObject result1 = null;
    @Override
    public void postSuccessMsg(String msg, String request_tag) {

        Log.d("LM", "标签" + request_tag + "请求成功：" + msg);
        if (request_tag.equals(Tag_Get_Locations1)) {
            result1 = null;
            JSONObject entity = null;
            JSONObject jo= JSON.parseObject(msg);
            try {
                result1 = JSON.parseObject(new String(AES256Utils.base64Decode(jo.getString("result"))));
                entity = result1.getJSONObject("entity");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (result1.getString("code").equals(0) || result1.getString("code").equals("0")) {
                JSONArray scanLabelInfo = entity.getJSONArray("orderDetailArray");
                Content0(entity.getJSONObject("orderInfo"), scanLabelInfo );
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext,result1.getString("detail"), Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    private void getPrintData(String scanRes) throws UnsupportedEncodingException
    {

        if (scanRes == null || scanRes.equals("")) {
            showToastMsg("未识别到单号，请重新扫描");
            finish();
            return;
        }
//        Authorization cellphone
        Map<String, String> params = new HashMap<String, String>();

        params.put("clientOrderNo",scanRes);
        params.put("cellphone",cellphone);

        Map<String, Object> entity = new HashMap<String, Object>();

        entity.put("entity",params);

        Map<String, String> param = new HashMap<String, String>();

        Log.d("LM", "getPath:entity的值 " + JSONObject.toJSONString(entity));

        param.put("param", AES256Utils.base64Encode(JSONObject.toJSONString(entity).getBytes()));

//        mClient.setShowToast(false);
        mClient.sendRequest(Constants.URL.SAAS_API_BASE + "kc-transport/tmsApp/selectOrderByClientOrderNo",  param, Tag_Get_Locations1, true, Authorization);
        Log.d("LM", "getPath: " + Constants.URL.SAAS_API_BASE);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
    public void Content0(JSONObject orderInfo, JSONArray scanLabelInfo){

        for (String key : orderInfo.keySet()) {
            if(orderInfo.get(key) == null){
                orderInfo.put(key, "");
            }
        }
        for (int i = 0; i < scanLabelInfo.size(); i++) {
            zkPrinter.setPage_CPCL(585, 750);//1650
            JSONObject productNo = (JSONObject) scanLabelInfo.get(i);
            try{
                print_1stLable(zkPrinter, 10, 0, 585,750, orderInfo, productNo.getString("productNo"));
                zkPrinter.print_CPCL(0, 1);
                // 记录是否打印和打印次数
                Map<String, Object> paramsprint = new HashMap<String, Object>();
                paramsprint.put("omsNo", orderInfo.getString("omsNo"));
                if(scanLabelInfo.size() == 1){
                    paramsprint.put("labelNo", productNo.getString("productNo"));
                }

                Map<String, String> paramres = new HashMap<String, String>();

                Map<String, Object> entity = new HashMap<String, Object>();

                entity.put("entity",paramsprint);

                paramres.put("param", AES256Utils.base64Encode(JSONObject.toJSONString(entity).getBytes()));

                mClient.sendRequest(Constants.URL.SAAS_API_BASE + "kc-transport/tmsApp/updatePrintCount", paramres, Tag_Get_Locations,false);

            }catch(Exception e){
                Log.d("LM", "顺店通打印报错" + e);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext,"请重新扫描", Toast.LENGTH_LONG).show();
                    }
                });
            }
//            zkPrinter.sendStatus();
        }
//        int a = zkPrinter.getStatus();
//        if(a==-1)
//        { //"获取状态异常------";
////            Toast.makeText(this,"获取状态异常-----", Toast.LENGTH_LONG).show();
//        }
//        if(a==1)
//        {//"缺纸----------";
////            Toast.makeText(this,"缺纸----------", Toast.LENGTH_LONG).show();
//        }
//        if(a==2)
//        {	//"开盖----------";
////            Toast.makeText(this,"开盖----------", Toast.LENGTH_LONG).show();
//        }
//        if(a==0)
//        {    	//"打印机正常-------";
////            Toast.makeText(this,"打印机正常-------", Toast.LENGTH_LONG).show();
//            Log.d("LM", "打印机正常 ");
////            zkPrinter.disconnect();
//        }
    }
    private void print_1stLable(zkBluetoothPrinter printer, int x, int y, int width, int height, JSONObject orderInfo,String itemCode)
    {
        int lineW=3;
        int publicH = 30;
        printer.drawBitmap_CPCL(x-12, 0, bitmap_logo, 0);
        y = y + publicH + 60;
        int verticalY = y-10;
        printer.drawLine_CPCL(x-12,y-10,x+width-40,y-10,lineW);
        printer.drawText_CPCL(x, y+15, "寄", 5, 0, true, false,false);//20
        String issuePartyTel = orderInfo.getString("issuePartyTel");
        issuePartyTel = (issuePartyTel!="")?(issuePartyTel.substring(0,3) + "****" + issuePartyTel.substring(7)) : "";
        String issuePartyGuHua = orderInfo.getString("issuePartyGuHua");
        issuePartyGuHua = (issuePartyGuHua!="")?(issuePartyGuHua.substring(0,issuePartyGuHua.length()-4) + "****"): "";
        String issuePartyTelLast = issuePartyTel!=""?issuePartyTel:issuePartyGuHua;
        printer.drawText_CPCL(x+60, y, orderInfo.getString("issuePartyContact") + "    " + issuePartyTelLast, 3, 0, false, false,false);//20
        y = y + publicH;
        printer.drawBoxText_CPCL(x+60, y,x+width-50, y+publicH+publicH,orderInfo.getString("issuePartyCity")+orderInfo.getString("issuePartyDistricict")+ orderInfo.getString("issuePartyAddr"), 3, false, false, 1,1);//20
        y = y + publicH+10+publicH;
        printer.drawLine_CPCL(x-12,y-10,x+width-40,y-10,lineW);
        printer.drawText_CPCL(x, y+15, "收", 5, 0, true, false,false);//20
        String receivePartyPhone = orderInfo.getString("receivePartyPhone");
        receivePartyPhone = (receivePartyPhone!="")?(receivePartyPhone.substring(0,3) + "****" + receivePartyPhone.substring(7)) : "";
        String receivePartyGuHua = orderInfo.getString("receivePartyGuHua");
        receivePartyGuHua = (receivePartyGuHua!="")?(receivePartyGuHua.substring(0,receivePartyGuHua.length()-4) + "****"): "";
        String receivePartyPhoneLast = receivePartyPhone!=""?receivePartyPhone:receivePartyGuHua;
        printer.drawText_CPCL(x+60, y, orderInfo.getString("receivePartyContactName")+ "    "+ receivePartyPhoneLast, 3, 0, false, false,false);//20
        y = y + publicH;
        printer.drawBoxText_CPCL(x+60, y, x+width-50,y+publicH+publicH,orderInfo.getString("receivePartyCity")+orderInfo.getString("receicePartyDistricict")+orderInfo.getString("receivePartyAddr1"), 3, false, false, 1,1);//20
        y = y + publicH + 10+publicH;
        int infoX = 270;
        printer.drawLine_CPCL(x-12,y-10,x+width-40,y-10,lineW);
        printer.drawText_CPCL(x, y, "品名：" + orderInfo.getString("productName"), 3, 0, false, false,false);//20
        printer.drawLine_CPCL(x+infoX-10,y-10,x+infoX-10,y+5*publicH,lineW);
        printer.drawText_CPCL(x+infoX, y, "月结卡号：" + orderInfo.getString("monthCardNumber"), 3, 0, false, false,false);//20
        y = y + publicH;
        printer.drawText_CPCL(x, y, "件数：" + orderInfo.getString("orderQty"), 3, 0, false, false,false);//20
        printer.drawText_CPCL(x+infoX, y, "付款方式：" + orderInfo.getString("chargeTypes"), 3, 0, false, false,false);//20
        y = y + publicH;
        printer.drawText_CPCL(x, y, "体积(m3)：" + orderInfo.getString("productSize"), 3, 0, false, false,false);//20
        printer.drawText_CPCL(x+infoX, y, "费用合计(元)：" + orderInfo.getString("orderAmount"), 3, 0, false, false,false);//20
        y = y + publicH;
        printer.drawText_CPCL(x, y,"计费重量(KG)：" + orderInfo.getString("chargeWeight"), 3, 0, false, false,false);//20
        printer.drawText_CPCL(x+infoX, y, "运费(元)：" + orderInfo.getString("transportFee"), 3, 0, false, false,false);//20
        y = y + publicH;
        printer.drawText_CPCL(x, y, "实际重量(KG)：" + orderInfo.getString("displayWt"), 3, 0, false, false,false);//20
        if (orderInfo.getString("returnBillFlag").equals("是")) {
           printer.drawText_CPCL(x+infoX, y, "电子签单", 3, 0, false, false,false);//20
        }
        y = y + publicH+10;
        printer.drawLine_CPCL(x-12,y-10,x+width-40,y-10,lineW);
        printer.drawText_CPCL(x, y, "签收时间：" + orderInfo.getString("deliveryDate"), 3, 0, false, false,false);//20
        y = y + publicH;
        printer.drawText_CPCL(x, y, "打印时间：" + orderInfo.getString("nowTime"), 3, 0, false, false,false);//20
        y = y + publicH;
        printer.drawBoxText_CPCL(x, y,x+width-50,y+publicH+publicH, "备注：" + orderInfo.getString("remark"), 3, false, false, 1,1);//20
        y = y + publicH+publicH+12;
        printer.drawLine_CPCL(x-12,y-10,x+width-40,y-10,lineW);
        printer.DrawBarcode1D_CPCL(x+20, y+10, itemCode, "128", 2, 80, 0);
        y = y + publicH+70;
        printer.drawText_CPCL(x+100, y, "子单号：" + itemCode, 3, 0, false, false,false);//20
        printer.drawLine_CPCL(x-12,y+8 +publicH,x+width-40,y+8 +publicH,lineW);
        printer.drawLine_CPCL(x-12,verticalY,x-5,y+10 +publicH,lineW);
        printer.drawLine_CPCL(x+width-40,verticalY,x+width-40,y+10 +publicH,lineW);
    }
    public boolean ListBluetoothDevice()
    {

        final List<Map<String,String>> list=new ArrayList<Map<String, String>>();

        ListView listView = (ListView) findViewById(R.id.listView1);

        SimpleAdapter m_adapter = new SimpleAdapter( this,list,
                android.R.layout.simple_list_item_2,
                new String[]{"DeviceName","BDAddress"},
                new int[]{android.R.id.text1,android.R.id.text2}
        );

        listView.setAdapter(m_adapter);

        if((myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter())==null)
        {
            Toast.makeText(this,"没有找到蓝牙适配器", Toast.LENGTH_LONG).show();
            return false;
        }

        if(!myBluetoothAdapter.isEnabled())
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 2);
        }

        Set <BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() <= 0)return false;
        for (BluetoothDevice device : pairedDevices)
        {
            Map<String,String> map=new HashMap<String, String>();
            map.put("DeviceName", device.getName());
            map.put("BDAddress", device.getAddress());
            list.add(map);
        }
        listView.setOnItemClickListener(new ListView.OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
            {
                SelectedBDAddress = list.get(arg2).get("BDAddress");
                if (((ListView)arg0).getTag() != null){
                    ((View)((ListView)arg0).getTag()).setBackgroundDrawable(null);
                }
                ((ListView)arg0).setTag(arg1);
                arg1.setBackgroundColor(getResources().getColor(R.color.mineblue));

            }
        });
        return true;
    }

    //    @Override
    public void showLoadingDialog() {
        if (myLoadingDialog == null) {
            myLoadingDialog = new MyLoadingDialog(this);
        }
//        cancelLoadingDialog();
        myLoadingDialog.showDialog();
    }

    //    @Override
    public void cancelLoadingDialog() {
        if (myLoadingDialog != null && myLoadingDialog.isShowing()) {
            myLoadingDialog.dismiss();
        }
    }

    //    生成条形码
    public static Bitmap createBarcode(String content,int cheight) {
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, 2000, cheight);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                int offset = y * width;
                for (int x = 0; x < width; x++) {
                    pixels[offset + x] = bitMatrix.get(x, y) ? 0xff000000 : 0xFFFFFFFF;
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
    //    生成二维码
    public static Bitmap createQRCode(String text, int size) {
        try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = new QRCodeWriter().encode(text,BarcodeFormat.QR_CODE, size, size, hints);
            int[] pixels = new int[size * size];
            for (int y = 0; y < size; y++) {
                for (int x = 0; x < size; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * size + x] = 0xff000000;
                    } else {
                        pixels[y * size + x] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(size, size,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

}
